<?php


namespace WXAPI\Controller;

use Api\Logic\GoodsLogic;
use Think\Page;

vendor('grafika.autoloader');

use Grafika\Color;
use Grafika\Grafika;
use Grafika\GrafikaHelper;
use Grafika\Curl;

class DefaultController extends BaseController
{


    /**
     * 获取商品列表
     */
    public function goodsLists()
    {
        $list = M('miaosha_goods')->where(['start_time'=>$_GET['time'],'open_time'=>date('Y-m-d')])->select();
        if (empty($list)) {
            exit(json_encode([
                'status' => 0,
                'msg' => '暂无秒杀活动'
            ]));
        }
		//20190103  维亚轩shadow 修复 时间大于10:00前秒杀商品不能购买问题
		
		$str=strlen($_GET['time']);
		if($str<5){
			$_GET['time']="0".$_GET['time'];
		}
		//20190103   维亚轩shadow 修复 时间大于10:00前秒杀商品不能购买问题
		
        if(date('H').':00' == $_GET['time']){
            $stt = 1;
        }else{
            $stt = 0;
        }

        foreach ($list as $k => $v) {
            $list[$k]['attr'] = json_decode($list[$k]['attr'], true);
            $list[$k]['sell_num'] = M('order_goods')->where(array('prom_type'=>4,'prom_id'=>$v['id']))->getField('sum(goods_num)');
            $list[$k]['stt'] = $stt;
            if(!$list[$k]['sell_num']){
                $list[$k]['sell_num'] = 0;
            }
            if($list[$k]['ms_num'] > $list[$k]['sell_num']){
                $list[$k]['status'] = 1;
            }else{
                $list[$k]['status'] = 0;
                $list[$k]['sell_num'] = 0;
            }
	    $list[$k]['attr']['original_img'] = 'https://'.$_SERVER['HTTP_HOST'].$list[$k]['attr']['original_img'];
        }
        exit(json_encode(array('status' => 1, 'msg' => '获取成功', 'result' => $list)));
    }
    
    public function getStoreinfo($store_id)
    {
        $reurn = array();
        $store = M('store')->where("store_id=$store_id")->field('store_id,store_logo,store_name,sc_id,store_desccredit,store_servicecredit,store_deliverycredit,store_phone,grade_id,la,lo,store_address')->find();
        $reurn['sc_name'] = M('store_class')->where(array('sc_id' => $store['sc_id']))->getField('sc_name');//分类
        $reurn['sg_name'] = M('store_grade')->where(array('sc_id' => $store['grade_id']))->getField('sg_name');//店铺等级
        $reurn['store_logo'] = SITE_URL . $store['store_logo'];
        $reurn['store_name'] = $store['store_name'];
        $reurn['store_desccredit'] = $store['store_desccredit'];
        $reurn['store_servicecredit'] = $store['store_servicecredit'];
        $reurn['store_deliverycredit'] = $store['store_deliverycredit'];
        $reurn['store_phone'] = $store['store_phone'];
        $reurn['la'] = $store['la'];
        $reurn['lo'] = $store['lo'];
        $reurn['store_address'] = $store['store_address'];
        return $reurn;
    }
    /**
     *  goodsPriceBySpec 获取商品价格
     */
    /*
    public function goodsPriceBySpec()
    {        
        $goods_id = I("goods_id"); // 商品id
        $goods_num = I("goods_num");// 商品数量
        $goods = M('Goods')->where("goods_id = $goods_id")->find();
        $goods_price = $goods['shop_price']; // 商品价格 
        
        // 有选择商品规格
        if(!empty($_REQUEST['spec_list']))
        {
            $spec_item = explode(',', $_REQUEST['spec_list']);
            sort($spec_item);
            $spec_item_key = implode('_', $spec_item);
            $specGoodsPrice = M("SpecGoodsPrice")->where("goods_id = $goods_id and `key` = '$spec_item_key'")->find();
            if($specGoodsPrice)
                $goods_price = $specGoodsPrice['price'];
        }    
        $price = $goods_price * $goods_num; // 商品单价乘以数量        
        
        if(!$price){
            $json_arr = array('status'=>-1,'msg'=>'没有查询到价格','result'=>'');
        }else{
            $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$price);
        }
        $json_str = json_encode($json_arr);
        exit($json_str);         
    }
    */

    /**
     *  获取商品的缩略图
     */
    function goodsThumImages()
    {
        $goods_id = I('goods_id');
        $width = I('width');
        $height = I('height');
        $img_url = SITE_URL . goods_thum_images($goods_id, $width, $height);
        $image = file_get_contents($img_url);  //假设当前文件夹已有图片001.jpg        
        header('Content-type: image/jpg');
        exit($image);
    }


    /**
     * 获取某个商品的评价
     */
    function getGoodsComment()
    {
        $goods_id = I('goods_id');
        $where = " goods_id = $goods_id  and is_show = 1";
        $count = M('comment')->where($where)->count();
        $_GET['p'] = $_REQUEST['p'];
        $page = new Page($count, 10);
        $list = M('comment')->where($where)->order("comment_id desc")->limit("{$page->firstRow},{$page->listRows}")->select();
        foreach ($list as $key => $val) {
            if (empty($val['img'])) {
                $list[$key]['img'] = '';
                continue;
            }

            $val['img'] = unserialize($val['img']);

            foreach ($val['img'] as $k => $v) {
                $val['img'][$k] = SITE_URL . $v;
            }
            $list[$key]['img'] = $val['img'];
        }
        exit(json_encode(array('status' => 1, 'msg' => '获取成功', 'result' => $list)));
    }

    /**
     * 收藏商品
     */
    function collectGoods()
    {
        $this->user_id = I('user_id');
        $goods_id = I('goods_id');
        $type = I('type', 0);
        $count = M('Goods')->where("goods_id = $goods_id")->count();
        if ($count == 0) exit(json_encode(array('status' => 1, 'msg' => '收藏商品不存在', 'result' => array())));
        //删除收藏商品
        if ($type == 1) {

            M('GoodsCollect')->where("user_id = {$this->user_id} and goods_id = $goods_id")->delete();
            exit(json_encode(array('status' => 1, 'msg' => '成功取消收藏', 'result' => array())));
        }
        $count = M('GoodsCollect')->where("user_id = {$this->user_id} and goods_id = $goods_id")->count();
        if ($count > 0) exit(json_encode(array('status' => 1, 'msg' => '您已收藏过该商品', 'result' => array())));
        M('GoodsCollect')->add(array(
            'goods_id' => $goods_id,
            'user_id' => $this->user_id,
            'add_time' => time(),
        ));
        exit(json_encode(array('status' => 1, 'msg' => '收藏成功', 'result' => array())));
    }


    /**
     * 猜你喜欢/热门推荐
     */
    public function guessYouLike()
    {
        $p = I('p', 1);
        $favourite_goods = M('goods')->where("is_recommend=1 and is_on_sale=1")->order('goods_id DESC')->page($p, 10)->getField('goods_id,cat_id,goods_sn,goods_name,shop_price,comment_count');//首页/购物车/我的 推荐商品
        $goods = array();
        foreach ($favourite_goods as $k => $v) {
            $goods[] = $v;
        }
        $json_arr = array('status' => 1, 'msg' => '获取成功', 'result' => $goods);
        $json_str = json_encode($json_arr, true);

        exit($json_str);
    }

    //生成商品二维码
    public function goodsQrcode()
    {

        $goods_id = I('goods_id');
        $user_id = I('user_id');
        $goods = M("goods")->where("goods_id=$goods_id")->find();
        if (!$goods) {
            $json_arr = array('code' => 1, 'msg' => '商品不存在');
            $json_str = json_encode($json_arr, true);
            exit($json_str);
        }
        //$store = Store::findOne($this->store_id);

        $goods_pic_url = M("goods_images")->where("goods_id=$goods_id")->getField("image_url");
        $goods_pic_url = SITE_URL . $goods_pic_url;
        $goods_pic_save_path = QRCODE_PATH . '/qrcode';
        $goods_pic_save_name = md5("v=1.6.2&goods_id={$goods['goods_id']}&goods_name={$goods['goods_name']}&store_name={$goods['store_id']}&user_id={$user_id}&goods_pic_url={$goods_pic_url}") . '.jpg';
        $pic_url = SITE_URL . "/Public/goodsqrcode/qrcode" . $goods_pic_save_name;
        if (file_exists($goods_pic_save_path . $goods_pic_save_name)) {

            $json_arr = array('code' => 0, 'msg' => '获取成功', 'data' => [
                'goods_name' => $goods['goods_name'],
                'pic_url' => $pic_url . '?v=' . time(),
            ]);
            $json_str = json_encode($json_arr, true);
            exit($json_str);
        }
        $goods_pic_path = $this->saveTempImage($goods_pic_url);
        if (!$goods_pic_path) {
            $json_arr = array('code' => 1, 'msg' => '获取商品海报失败：商品图片丢失');
            $json_str = json_encode($json_arr, true);
            exit($json_str);
        }
        $goods_qrcode_dst = 'Public/qrcode/goods-qrcode-dst.jpg';
        $font_path = 'Public/fonts/st-heiti-light.ttc';

        $editor = Grafika::createEditor(GrafikaHelper::getSupportEditorLib());
        $editor->open($goods_qrcode, $goods_qrcode_dst);
        $editor->open($goods_pic, $goods_pic_path);

        //获取小程序码图片

        $wxapp_qrcode_file_res = $this->getQrcode($goods['goods_id'], $user_id);

        if ($wxapp_qrcode_file_res['code'] == 1) {
            unlink($goods_pic_path);
            return [
                'code' => 1,
                'msg' => '获取商品海报失败：获取小程序码失败，' . $wxapp_qrcode_file_res['msg'],
            ];
        }
        $wxapp_qrcode_file_path = $wxapp_qrcode_file_res['file_path'];
        $editor->open($wxapp_qrcode, $wxapp_qrcode_file_path);

        $name_size = 30;
        $name_width = 670;
        //商品名称处理换行
        $name = $this->autowrap($name_size, 0, $font_path, $goods['goods_name'], $name_width, 2);
        //加商品名称
        $editor->text($goods_qrcode, $name, $name_size, 40, 750, new Color('#333333'), $font_path, 0);

        //裁剪商品图片
        //$editor->crop($goods_pic, 670, 670, 'smart');
        $editor->resizeFill($goods_pic, 670, 670);
        //附加商品图片
        $editor->blend($goods_qrcode, $goods_pic, 'normal', 1.0, 'top-left', 40, 40);

        //加商品价格
        $editor->text($goods_qrcode, '￥' . $goods['shop_price'], 45, 30, 910, new Color('#ff4544'), $font_path, 0);

        //加商城名称
        $editor->text($goods_qrcode, $store->name, 20, 40, 1170, new Color('#888888'), $font_path, 0);

        //调整小程序码图片
        $editor->resizeExactWidth($wxapp_qrcode, 240);
        //附加小程序码图片
        $editor->blend($goods_qrcode, $wxapp_qrcode, 'normal', 1.0, 'top-left', 470, 1040);

        //保存图片
        $editor->save($goods_qrcode, $goods_pic_save_path . $goods_pic_save_name, 'jpeg', 85);

        //删除临时图片
        unlink($goods_pic_path);
        unlink($wxapp_qrcode_file_path);
        $json_arr = array('code' => 0, 'msg' => '获取成功', 'data' => [
            'goods_name' => $goods['goods_name'],
            'pic_url' => $pic_url . '?v=' . time(),
        ]);
        $json_str = json_encode($json_arr, true);
        exit($json_str);
    }

    private function getQrcode($goods_id, $user_id)
    {
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        $config_value = unserialize($paymentPlugin['config_value']);
        $APPID = $config_value['appid'];
        $SECRET = $config_value['appsecret'];
        $api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$APPID}&secret={$SECRET}";
        $res = $this->curl_get($api);
        $res = json_decode($res, true);

        if (empty($res['access_token'])) {

            return false;
        }

        $accessToken = $res['access_token'];
        $api = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
        $curl = new Curl();
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
        $data = json_encode([
            'scene' => "gid:{$goods_id},uid:{$user_id}",
            'page' => 'pages/goods/detail/detail',
            'width' => 240,
        ]);
        $curl->post($api, $data);
        if (in_array('Content-Type: image/jpeg', $curl->response_headers)) {
            //返回图片

            $json_arr = array('code' => 0, 'msg' => '获取成功', 'file_path' => $this->saveTempImageByContent($curl->response));

            return $json_arr;
        } else {
            //返回文字
            $res = json_decode($curl->response, true);
            $json_arr = array('code' => 0, 'msg' => $res['errmsg']);

            return $json_arr;
        }
    }

    //保存图片内容到临时文件
    private function saveTempImageByContent($content)
    {
        $save_path = QRCODE_PATH . '/image/' . md5(base64_encode($content)) . '.jpg';
        $fp = fopen($save_path, 'w');
        fwrite($fp, $content);
        fclose($fp);
        return $save_path;
    }

    //获取网络图片到临时目录
    private function saveTempImage($url)
    {
        $wdcp_patch = false;
        //$wdcp_patch_file = \Yii::$app->basePath . '/patch/wdcp.json';
        if (file_exists($wdcp_patch_file)) {
            $wdcp_patch = json_decode(file_get_contents($wdcp_patch_file), true);
            if ($wdcp_patch && in_array(\Yii::$app->request->hostName, $wdcp_patch)) {
                $wdcp_patch = true;
            } else {
                $wdcp_patch = false;
            }
        }
        if ($wdcp_patch)
            $url = str_replace('http://', 'https://', $url);

        if (!is_dir(QRCODE_PATH . '/image'))
            mkdir(QRCODE_PATH . '/image');

        $save_path = QRCODE_PATH . '/image/' . md5($url) . '.jpg';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $img = curl_exec($ch);
        curl_close($ch);
        $fp = fopen($save_path, 'w');
        fwrite($fp, $img);
        fclose($fp);
        return $save_path;
    }

    private function return_json($state, $msg, $data = array())
    {

        $json_arr = array('code' => state, 'msg' => $msg, 'data' => $data);
        $json_str = json_encode($json_arr, true);
        exit($json_str);
    }

    private function curl_get($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $json_data = curl_exec($ch);
        curl_close($ch);
        return $json_data;
    }

    /**
     * @param integer $fontsize 字体大小
     * @param integer $angle 角度
     * @param string $fontface 字体名称
     * @param string $string 字符串
     * @param integer $width 预设宽度
     */
    private function autowrap($fontsize, $angle, $fontface, $string, $width, $max_line = null)
    {
        // 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
        $content = "";
        // 将字符串拆分成一个个单字 保存到数组 letter 中
        $letter = [];
        for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {
            $letter[] = mb_substr($string, $i, 1, 'UTF-8');
        }
        $line_count = 0;
        foreach ($letter as $l) {
            $teststr = $content . " " . $l;
            $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
            // 判断拼接后的字符串是否超过预设的宽度
            if (($testbox[2] > $width) && ($content !== "")) {
                $line_count++;
                if ($max_line && $line_count >= $max_line) {
                    $content = mb_substr($content, 0, -1, 'UTF-8') . "...";
                    break;
                }
                $content .= "\n";
            }
            $content .= $l;
        }
        return $content;
    }


}